# Copyright (c) 2017 Presto Labs Pte. Ltd.
# Author: leon

import time
import os

from coin.exchange.bittrex_v1.book_builder import BookBuilder
from coin.exchange.bittrex_v1.kr_rest.product import BittrexProduct
from bittrex_websocket.websocket_client import BittrexSocket


class BittrexHandler(BittrexSocket):
  def __init__(self, verbose=False):
    BittrexSocket.__init__(self)
    self._books = {}
    self._callback = lambda book: None
    self.verbose = verbose
    self.disable_log()

  def subscribe(self, symbols, callback):
    self._callback = callback
    self._symbols = [BittrexProduct.FromStr(symbol).native_symbol for symbol in symbols]
    self.subscribe_to_orderbook(self._symbols, 200)

  def on_orderbook(self, msg):
    # TODO(leon): Update book manually
    symbol = msg['MarketName']
    book = BookBuilder('Bittrex', symbol)
    bids = msg['Buys']
    asks = msg['Sells']
    book.snapshot(bids, asks)
    book.timestamp = int(time.time() * 1e9)
    self._ready = True
    self._books[symbol] = book
    self._callback(book)

  def stop(self):
    self.disconnect()

  def start(self):
    pass

  def on_close(self):
    # Called before closing the websocket instance.
    # Use it when you want to add any closing logic.
    print('Bittrex websocket closed.')
    os._exit(1)

  def on_error(self, error):
    # Error handler
    print('Bittrex socket error: ' + error)
    self.disconnect()
    os._exit(1)
